package training.io.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Penerima {
	private Socket socket;
	private BufferedReader reader;
	
	public Penerima(Integer port){
		try {
			ServerSocket serv = new ServerSocket(port);
			System.out.println("Menunggu koneksi di port "+port);
			socket = serv.accept();
			System.out.println("Ada client dari "+socket.getInetAddress().getHostAddress());
			reader = new BufferedReader(
					new InputStreamReader(socket.getInputStream()));
			
			String data;
			while((data = reader.readLine()) != null){
				System.out.println(data);
				if("exit".equalsIgnoreCase(data.trim())){
					break;
				}
			}
			stop();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void stop(){
		try {
			reader.close();
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
